<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  
  <title>异步 | 漠北烟云</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="由于js是单线程的语言，所以在执行时如何全部任由函数同步执行，这就会导致很多问题，页面加载慢，任务阻塞等等，这就要引入异步概念。异步在实现上，依赖一些特殊的语法规则。从整体上来说，异步方案经历了如下的四个进化阶段：回调函数 —&gt; Promise —&gt; Generator —&gt; async&#x2F;await。异步的使用确实带来了很多便利却也带来了很多问题，其中最为严重的就是回调">
<meta property="og:type" content="article">
<meta property="og:title" content="异步">
<meta property="og:url" content="http://example.com/2023/03/13/%E5%BC%82%E6%AD%A5/index.html">
<meta property="og:site_name" content="漠北烟云">
<meta property="og:description" content="由于js是单线程的语言，所以在执行时如何全部任由函数同步执行，这就会导致很多问题，页面加载慢，任务阻塞等等，这就要引入异步概念。异步在实现上，依赖一些特殊的语法规则。从整体上来说，异步方案经历了如下的四个进化阶段：回调函数 —&gt; Promise —&gt; Generator —&gt; async&#x2F;await。异步的使用确实带来了很多便利却也带来了很多问题，其中最为严重的就是回调">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2023-03-13T14:06:51.000Z">
<meta property="article:modified_time" content="2023-03-26T14:54:31.835Z">
<meta property="article:author" content="mobeiyanyun">
<meta property="article:tag" content="js基础">
<meta name="twitter:card" content="summary">
  
    <link rel="alternate" href="/atom.xml" title="漠北烟云" type="application/atom+xml">
  
  
    <link rel="shortcut icon" href="/favicon.png">
  
  
    
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/typeface-source-code-pro@0.0.71/index.min.css">

  
  
<link rel="stylesheet" href="/css/style.css">

  
    
<link rel="stylesheet" href="/fancybox/jquery.fancybox.min.css">

  
<meta name="generator" content="Hexo 6.3.0"></head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">漠北烟云</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://example.com"></form>
      </div>
    </div>
  </div>
</header>

      <div class="outer">
        <section id="main"><article id="post-异步" class="h-entry article article-type-post" itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
  <div class="article-meta">
    <a href="/2023/03/13/%E5%BC%82%E6%AD%A5/" class="article-date">
  <time class="dt-published" datetime="2023-03-13T14:06:51.000Z" itemprop="datePublished">2023-03-13</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="p-name article-title" itemprop="headline name">
      异步
    </h1>
  

      </header>
    
    <div class="e-content article-entry" itemprop="articleBody">
      
        <p>由于js是单线程的语言，所以在执行时如何全部任由函数同步执行，这就会导致很多问题，页面加载慢，任务阻塞等等，这就要引入异步概念。<br>异步在实现上，依赖一些特殊的语法规则。从整体上来说，异步方案经历了如下的四个进化阶段：<br><strong>回调函数 —&gt; Promise —&gt; Generator —&gt; async&#x2F;await。</strong><br>异步的使用确实带来了很多便利却也带来了很多问题，其中最为严重的就是回调地狱问题，例如B()依赖于 A()就形成</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="title">A</span></span> () &#123;</span><br><span class="line">    <span class="function"><span class="title">B</span></span>()&#123;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如果再多点</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="title">A</span></span> () &#123;</span><br><span class="line">   <span class="function"><span class="title">B</span></span>()&#123;</span><br><span class="line">        <span class="function"><span class="title">C</span></span>()&#123;</span><br><span class="line">             <span class="function"><span class="title">D</span></span>()&#123;</span><br><span class="line">               &#125;</span><br><span class="line">           &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>可读性极差<br>Promise的出现很好的解决了这个问题<br>Promise 会接收一个执行器，在这个执行器里，我们需要把目标的异步任务给”填进去“。<br>在 Promise 实例创建后，执行器里的逻辑会立刻执行，在执行的过程中，根据异步返回的结果，决定如何使用 resolve 或 reject 来改变 Promise实例的状态。 Promise 实例有三种状态：</p>
<ul>
<li>pending状态，表示进行中。这是 Promise 实例创建后的一个初始态；</li>
<li>fulfilled 状态，表示成功完成。这是我们在执行器中调用 resolve 后，达成的状态；</li>
<li>rejected 状态，表示操作失败、被拒绝。这是我们在执行器中调用 reject后，达成的状态；</li>
</ul>
<p>有了promise 就可以通过链式调用解决以上问题</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">A ().<span class="keyword">then</span>(res=&gt;&#123;</span><br><span class="line">    <span class="built_in">return</span> B()</span><br><span class="line">&#125;) .<span class="keyword">then</span>(res=&gt;&#123;</span><br><span class="line">    <span class="built_in">return</span> C()</span><br><span class="line">&#125;).<span class="keyword">then</span>(res=&gt;&#123;</span><br><span class="line">    <span class="built_in">return</span> D()   </span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>除此之外Promise也提供了一些方法：</p>
<h5 id="Promise-all"><a href="#Promise-all" class="headerlink" title="Promise.all:"></a>Promise.all:</h5><p>p1,p2,p3 全部为fulfilled 时返回 fulfilled</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">var p = Promise.all([p1,p2,p3]).<span class="keyword">then</span>(res=&gt;&#123;</span><br><span class="line"></span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<h5 id="Promise-race"><a href="#Promise-race" class="headerlink" title="Promise.race"></a>Promise.race</h5><p>p1,p2,p3 有一个为race时返回 fulfilled</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">var p = Promise.race([p1,p2,p3]).<span class="keyword">then</span>(res=&gt;&#123;&#125;);</span><br></pre></td></tr></table></figure>
<h5 id="Promise-resolve"><a href="#Promise-resolve" class="headerlink" title="Promise.resolve"></a>Promise.resolve</h5><p>有时需要将现有对象转为Promise对象，Promise.resolve方法就起到这个作用。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">var Promise = Promise.resolve($.ajax(<span class="string">&#x27;/whatever.json&#x27;</span>));</span><br></pre></td></tr></table></figure>
<h5 id="Promise-rejected"><a href="#Promise-rejected" class="headerlink" title="Promise.rejected"></a>Promise.rejected</h5><p>Promise.reject(reason)方法也会返回一个新的Promise实例，该实例的状态为rejected。Promise.reject方法的参数reason，会被传递给实例的回调函数。<br>上面代码将 jQuery 生成 deferred 对象，转为一个新的 ES6 的 Promise 对象。<br>如果 Promise.resolve 方法的参数，不是具有 then 方法的对象（又称 thenable 对象），则返回一个新的 Promise 对象，且它的状态为fulfilled</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">var p = Promise.reject(<span class="string">&#x27;出错了&#x27;</span>); p.then(null, <span class="keyword">function</span> (s)&#123; console.log(s) &#125;); // 出错了</span><br></pre></td></tr></table></figure>
<p>async&#x2F;await 和 generator 方案，相较于 Promise 而言，有一个重要的优势：Promise 的错误需要通过回调函数捕获，try catch 是行不通的。而 async&#x2F;await 和 generator 允许 try&#x2F;catch。</p>
<style>
    blockquote {
        margin:1.6em 0px !important;
        text-align: left !important;
    }
</style>
<blockquote>
真正的力量，永远不会属于天生就强壮过人、敏捷过人、聪明过人的家伙，它只会属于愿意不惜一切，达成目的的人。
———希尔科
</blockquote>



      
    </div>
    <footer class="article-footer">
      <a data-url="http://example.com/2023/03/13/%E5%BC%82%E6%AD%A5/" data-id="clfziy0or000dp5r4gzad0bku" data-title="异步" class="article-share-link">Share</a>
      
      
      
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/js%E5%9F%BA%E7%A1%80/" rel="tag">js基础</a></li></ul>

    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2023/03/14/%E9%98%9F%E5%88%97%E5%92%8C%E6%A0%88/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          队列和栈
        
      </div>
    </a>
  
  
    <a href="/2023/03/12/for-await-of/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">for-await-of</div>
    </a>
  
</nav>

  
</article>


</section>
        
          <aside id="sidebar">
  
    

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tags</h3>
    <div class="widget">
      <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/tags/VUE/" rel="tag">VUE</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/js%E5%9F%BA%E7%A1%80/" rel="tag">js基础</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E5%B0%8F%E7%A8%8B%E5%BA%8F-uniapp/" rel="tag">小程序&#x2F;uniapp</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E6%B7%B7%E5%90%88%E5%BC%80%E5%8F%91/" rel="tag">混合开发</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tag Cloud</h3>
    <div class="widget tagcloud">
      <a href="/tags/VUE/" style="font-size: 15px;">VUE</a> <a href="/tags/js%E5%9F%BA%E7%A1%80/" style="font-size: 20px;">js基础</a> <a href="/tags/%E5%B0%8F%E7%A8%8B%E5%BA%8F-uniapp/" style="font-size: 10px;">小程序/uniapp</a> <a href="/tags/%E6%B7%B7%E5%90%88%E5%BC%80%E5%8F%91/" style="font-size: 10px;">混合开发</a>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2023/04/">April 2023</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2023/03/">March 2023</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2023/04/02/%E5%B0%8F%E7%A8%8B%E5%BA%8F%E7%99%BB%E5%BD%95%E8%AE%BE%E8%AE%A1/">小程序登录设计</a>
          </li>
        
          <li>
            <a href="/2023/03/30/%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F/">vue中的观察者模式</a>
          </li>
        
          <li>
            <a href="/2023/03/29/%E6%95%B0%E6%8D%AE%E5%8F%98%E6%9B%B4%E7%9A%84%E7%9B%91%E6%B5%8B/">数据变更的监测</a>
          </li>
        
          <li>
            <a href="/2023/03/26/%E9%97%AD%E5%8C%85/">闭包</a>
          </li>
        
          <li>
            <a href="/2023/03/21/instanceof%E5%8E%9F%E7%90%86/">instanceof原理</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      
      &copy; 2023 mobeiyanyun<br>
      Powered by <a href="https://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>

    </div>
    <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    


<script src="/js/jquery-3.4.1.min.js"></script>



  
<script src="/fancybox/jquery.fancybox.min.js"></script>




<script src="/js/script.js"></script>





  </div>
</body>
</html>